package com.kedou.sdk.ui.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.kedou.sdk.JuHaoWanSDK;
import com.kedou.sdk.assist.CallbackObservable;
import com.kedou.sdk.assist.Constant;
import com.kedou.sdk.content.IActivityContent;
import com.kedou.sdk.core.HttpEngineApi;
import com.kedou.sdk.core.HttpEngineConduits;
import com.kedou.sdk.params.ActivityResponseParams;
import com.kedou.sdk.params.RedPackageBindResponseParams;
import com.kedou.sdk.params.RedPackageCashOutResponseParams;
import com.kedou.sdk.params.RedPackageGetResponseParams;
import com.kedou.sdk.params.RedpackageResponseParams;
import com.kedou.sdk.params.ResponseParams;
import com.kedou.sdk.params.bean.AccountInfo;
import com.kedou.sdk.params.bean.ActivityInfo;
import com.kedou.sdk.params.bean.NavModel;
import com.kedou.sdk.params.bean.State;
import com.kedou.sdk.params.bean.WindowMessage;
import com.kedou.sdk.params.bean.WindowMessageType;
import com.kedou.sdk.ui.assist.ActivityListAdapter;
import com.kedou.sdk.ui.fragment.ChangeFragmentLister;
import com.kedou.sdk.ui.fragment.RedPackageBindFragment;
import com.kedou.sdk.ui.fragment.RedPackageDetailFragment;
import com.kedou.sdk.ui.fragment.RedPackageFragment;
import com.kedou.sdk.ui.fragment.RedPackageTixianFragment;
import com.kedou.sdk.ui.model.ActivityPageInfo;
import com.kedou.sdk.ui.model.TabReadStatus;
import com.kedou.sdk.ui.view.DialogFactory;
import com.kedou.sdk.utils.ResUtils;
import com.kedou.sdk.utils.ToolsUtils;
import com.kedou.sdk.utils.WL;
import com.kedou.sdk.utils.XmlUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2017/6/13 0013.
 */
public class FloatExtensionBarActivity extends AppBaseActivity implements ViewTreeObserver.OnGlobalLayoutListener,
        View.OnClickListener, AdapterView.OnItemClickListener {

    private static final String TAG = FloatExtensionBarActivity.class.getSimpleName();

    private static final String QQ_CUSTOMER_SERVICE = "http://wpd.b.qq.com/page/webchat.html";
    private static final String WECHAT_PUBLIC_NUMBER = "http://www.51wansy.sdkv3.com/";

    private final HashMap<String, String> mLoadUrlStack = new HashMap<String, String>();

    private ViewStub mTabbarView, mContentView;
    private TextView mContentTitle;
    private ImageButton mContentWebViewGoback;
//    private ListView mContentLocalView;
    private FrameLayout mContentRemoteView;
    private WebView mContentWebView;
    private ProgressBar mContentProgressBar;
    private List<Button> mDividers;
    private List<ImageView> mDividerDots;

    private View mDrawerDivider;
    private View mDrawerContent;
    private View mInflatTabbarViewStub;
    private View mInflatContentViewStub;

    private ViewTreeObserver mViewTreeObserver;

    private ActivityListAdapter mActivityListAdapter;

    private ExtensionBarBroadcastReceiver mReceiver;
    private boolean isAnimationLoading = false;
    private List<ActivityInfo> mActivityInfoList = new ArrayList<>();

    private FrameLayout redPackageLayout;

    public static String getValueByName(String url, String name) {
        String result = "";
        int index = url.indexOf("?");
        String temp = url.substring(index + 1);
        String[] keyValue = temp.split("&");
        for (String str : keyValue) {
            if (str.contains(name)) {
                result = str.replace(name + "=", "");
                break;
            }
        }
        return result;
    }
    List<NavModel> navModels;
    private  int defaultNav;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutIdentifier("wan_activity_float_extensionbar"));
        navModels =HttpEngineApi.getInstance().getEngineConduits().getPlatformConfigInfo().getNav_list();
        for(int i=0;i<navModels.size();i++){
            if(navModels.get(i).getIs_default()==1){
                defaultNav=i;
                break;
            }
        }
        onInitViews();
        width = ResUtils.dip2px(getApplicationContext(),280);
        mReceiver = new ExtensionBarBroadcastReceiver();
        IntentFilter fliter = new IntentFilter(Constant.LocalIntentAction.DESTROY_FLOAT_EXTENSIONBAR);
        LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, fliter);

//        HttpEngineApi.getInstance().getGameActivityInfo(requestCallbackHandler(ActivityResponseParams.class));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
    }

    private WindowMessage getIntentWindowMessage() {
        WindowMessage message = null;
        Intent intent = getIntent();
        if (intent != null) {
            message = intent.getParcelableExtra(Constant.LocalIntentExtra.INTENT_FLOAT_WINDOW_DATA);
        }
        return message;
    }

    private void onInitViews() {
        mDrawerContent = findViewById(getViewIdentifier("activity_extendsionbar_drawer_content"));
        mDrawerDivider = findViewById(getViewIdentifier("activity_extendsionbar_drawer_divider"));
        mTabbarView = (ViewStub) findViewById(getViewIdentifier("activity_extendsionbar_tabhost_vs"));
        mContentView = (ViewStub) findViewById(getViewIdentifier("activity_extendsionbar_content_vs"));

        mViewTreeObserver = mDrawerDivider.getViewTreeObserver();
        if (mViewTreeObserver != null && mViewTreeObserver.isAlive()) {
            mViewTreeObserver.addOnGlobalLayoutListener(this);
        }
    }

    @Override
    public void onBackPressed() {
        WL.d(TAG, "onBackPressed  --->");
        if (isDrawerOpen()) {
            closeDrawer();
        } else {
            super.onBackPressed();
        }
    }
    private RedpackageResponseParams.RedpackageResponseData redPackageinfo;
    @Override
    public void onAsyncRequestResult(int flag, ResponseParams response, Object... params) {
        super.onAsyncRequestResult(flag, response, params);
        if (response instanceof ActivityResponseParams) {
            ActivityResponseParams.ActivityResponseData data = (ActivityResponseParams.ActivityResponseData) response.getData();
            if (data != null && !data.isEmpty()) {
                mActivityInfoList.addAll(data.getActivityInfos());
                if (mActivityListAdapter != null) {
                    mActivityListAdapter.resetItemData(new ArrayList<IActivityContent>(mActivityInfoList));
                }
            }
        }else if (response instanceof RedpackageResponseParams){
            // 通过FragmentManager对象获得FragmentTransaction对象(开启事务)
            if (State.SUCCESS == response.getCode()) {
                redPackageinfo = (RedpackageResponseParams.RedpackageResponseData)response.getData();
                if(redpackage.isVisible()){
                    redpackage.updateDate(redPackageinfo);
                }else{
                    redpackage.updateDate(redPackageinfo);
                Bundle bundle = new Bundle();
                bundle.putParcelable("date",redPackageinfo);
                redpackage.setArguments(bundle);
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                    fragmentTransaction.replace(redPackageLayout.getId(),redpackage);//动态添加
                    fragmentTransaction.commit();//提交  提交  提交（很重要）
                }

            }else {
                Toast.makeText(FloatExtensionBarActivity.this,response.getMsg(),Toast.LENGTH_SHORT).show();
            }

        }else if (response instanceof RedPackageGetResponseParams){
            if (State.SUCCESS == response.getCode()) {
                Toast.makeText(FloatExtensionBarActivity.this,"领取成功",Toast.LENGTH_SHORT).show();
                changeFragmentLister.changeToMain();
            }else {
                Toast.makeText(FloatExtensionBarActivity.this,response.getMsg(),Toast.LENGTH_SHORT).show();
            }
        }else if (response instanceof RedPackageBindResponseParams){
            if (State.SUCCESS == response.getCode()) {
                redPackageinfo.setIs_bind_zfb(1);
//                redPackageinfo.setReal_name((String)params[0]);
//                redPackageinfo.setZfb_account((String)params[1]);
                Toast.makeText(FloatExtensionBarActivity.this,"绑定成功",Toast.LENGTH_SHORT).show();
                changeFragmentLister.changeToTixian();
            }else{
                Toast.makeText(FloatExtensionBarActivity.this,response.getMsg(),Toast.LENGTH_SHORT).show();
            }
        }else if (response instanceof RedPackageCashOutResponseParams){
            if (State.SUCCESS == response.getCode()) {
                Toast.makeText(FloatExtensionBarActivity.this,"请求成功,等待审核",Toast.LENGTH_SHORT).show();
                changeFragmentLister.changeToMain();
            }
//            else{
//                Toast.makeText(FloatExtensionBarActivity.this,response.getState().getMsg(),Toast.LENGTH_SHORT).show();
//            }
        }
    }

    public void hideFloatExtensionBar(View view) {
        WL.d(TAG, "hideFloatExtensionBar  ---> ");
        closeDrawer();
    }



    public void clickToNormalPage(String url) {
        checkContentView();
        setActivityCenterVisible(false);
        invalidateViewsStates(-1);
        mContentWebView.loadUrl(url);
    }

    public void clickToMenuView(String key,int index,boolean activityVisible,String appendString){
        checkContentView();

        setActivityCenterVisible(activityVisible);
        invalidateViewsStates(index);
        mContentWebView.loadUrl(HttpEngineApi.getInstance().getFloatMenuUrl(key)
                +(TextUtils.isEmpty(appendString)?"":appendString));
    }
    public void clickToMenuView(NavModel model){
        checkContentView();
        setActivityCenterVisible(false);
        for (int i=0;i<navModels.size();i++){
            if(model.getIden_name().equals(navModels.get(i).getIden_name())){
                invalidateViewsStates(i);
                break;
            }
        }
        mContentWebView.loadUrl(HttpEngineApi.getInstance().getFloatMenuUrl(model));
    }

    public void clickToActivityCenter(View view) {
        checkContentView();
//        setActivityCenterVisible(true);
        setActivityCenterVisible(true);
        invalidateViewsStates(-1);
        mContentWebView.loadUrl(HttpEngineApi.getInstance().getActivityHttpRequestUrl());
    }

    public void clickToUserAccount(View view) {
        clickToMenuView(navModels.get(0));
//        checkContentView();
//        setActivityCenterVisible(false);
//        invalidateViewsStates(0);
//        mContentWebView.loadUrl(HttpEngineApi.getInstance().getUserHttpRequestUrl());
    }

    public void clickToGameStrategy(View view) {
        clickToMenuView(navModels.get(1));
//        checkContentView();
//        setActivityCenterVisible(false);
//        invalidateViewsStates(1);
//        mContentWebView.loadUrl(HttpEngineApi.getInstance().getStrategyHttpRequestUrl());
    }

    public void clickToCustomService(View view) {
        clickToMenuView(navModels.get(2));
//        checkContentView();
//        setActivityCenterVisible(false);
//        invalidateViewsStates(2);
//        mContentWebView.loadUrl(HttpEngineApi.getInstance().getCustomServiceHttpRequestUrl());
    }

    public void clickToGameGifts(View view) {
        clickToMenuView(navModels.get(3));
//        checkContentView();
//        setActivityCenterVisible(false);
//        invalidateViewsStates(3);
//        mContentWebView.loadUrl(HttpEngineApi.getInstance().getGiftsHttpRequestUrl());
    }

    void invalidateViewsStates(final int position) {
        WL.e("TAG",position+"position");
        if (mDividers != null) {
            final int size = mDividers.size();
            for (int i = 0; i < size; i++) {
                if (position == i) {
                    mDividers.get(i).setSelected(true);
                } else {
                    mDividers.get(i).setSelected(false);
                }
            }
        }
        mLoadUrlStack.clear();
    }

    void checkContentView() {
        if (mContentView != null && mInflatContentViewStub == null) {
            mInflatContentViewStub = mContentView.inflate();
            mContentTitle = (TextView) findViewById(getViewIdentifier("activity_extendsionbar_content_title"));
//            mContentLocalView = findViewById(getViewIdentifier("activity_extendsionbar_content_local"));
            redPackageLayout = (FrameLayout) findViewById(getViewIdentifier("activity_extendsionbar_redPackage_layout"));
            mContentRemoteView = findViewById(getViewIdentifier("activity_extendsionbar_content_remote"));
            mContentProgressBar = (ProgressBar) findViewById(getViewIdentifier("activity_extendsionbar_content_progressbar"));
            mContentWebViewGoback = (ImageButton) findViewById(getViewIdentifier("activity_extendsionbar_content_goback"));
            mContentWebViewGoback.setOnClickListener(this);
            mContentWebView = (WebView) findViewById(getViewIdentifier("activity_extendsionbar_content_webview"));
            try {
                ImageView activityIcon = (ImageView)findViewById(getViewIdentifier("activity_extendsionbar_activity_image"));
                if(XmlUtils.isRedPackageChannel()&&activityIcon!=null){
                    activityIcon.setImageResource(ResUtils.getDrawableIdentifier(this,"wan_icon_float_extensionbar_land_hongbao"));
                }
            }catch (Exception e){
                e.printStackTrace();
            }


            WebSettings webSettings = mContentWebView.getSettings();
            webSettings.setUseWideViewPort(true);
            webSettings.setSupportZoom(true);
            webSettings.setAppCacheEnabled(false);
            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            webSettings.setJavaScriptEnabled(true);
            webSettings.setDomStorageEnabled(true);
            webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
            webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
            mContentWebView.setWebChromeClient(new ExtensionBarWebChromeClient());
            mContentWebView.setWebViewClient(new ExtensionBarWebViewClient());
            mContentWebView.addJavascriptInterface(new AndroidJavaScriptInterface(), "h5Game");

//            mActivityListAdapter = new ActivityListAdapter();
//            mActivityListAdapter.resetItemData(new ArrayList<IActivityContent>(mActivityInfoList));
//            mContentLocalView.setAdapter(mActivityListAdapter);
//            mContentLocalView.setOnItemClickListener(this);
        }
    }

    private void setTabDividerRedDotVisible(int position, boolean visible) {
        if (mDividerDots != null) {
            position = Math.max(Math.min(position, mDividerDots.size() - 1), 0);
            ImageView imageView = mDividerDots.get(position);
            if(imageView!=null)
            imageView.setVisibility(visible ? View.VISIBLE : View.INVISIBLE);
        }
    }
    int width ;
    private Drawable getNavDrawable(NavModel model){
        HashMap<String,Bitmap> menuBitmap = JuHaoWanSDK.getInstance().getMenuBitmap();
        try {
            StateListDrawable drawable =new StateListDrawable();
            WL.e("tag",menuBitmap.containsKey(model.getName()+"select")+".."+menuBitmap.containsKey(model.getName()));
            BitmapDrawable bitmapDrawableSele =new BitmapDrawable(getResources(),menuBitmap.get(model.getName()+"select"));

            BitmapDrawable bitmapDrawable =new BitmapDrawable(getResources(),menuBitmap.get(model.getName()));


            drawable.addState(new int[]{android.R.attr.state_selected},bitmapDrawableSele);
            drawable.addState(new int[]{-android.R.attr.state_selected},bitmapDrawable);

//            drawable.setBounds(0,0,500,500);
//            drawable.addState(new int[]{android.R.attr.state_selected}, getResources().getDrawable(R.drawable.wan_icon_extensionbar_strategy_press_port));
//            drawable.addState(new int[]{-android.R.attr.state_selected},getResources().getDrawable(R.drawable.wan_icon_extensionbar_strategy_press_port));
            return drawable;
        }catch (Exception e){
            e.printStackTrace();
            WL.e("tag","errro");
            return null;
        }

    }

    private void openDrawer() {
        if (!isDrawerOpen() && !isDrawerLoading()) {
            if (mTabbarView != null) {
                mInflatTabbarViewStub = mTabbarView.inflate();
                mDividers = new ArrayList<>();
                Button firstButton = (Button) findViewById(getViewIdentifier("activity_extendsionbar_divider_me"));
                firstButton.setCompoundDrawablesRelativeWithIntrinsicBounds(null,getNavDrawable(navModels.get(0)),null,null);
                firstButton.setText(navModels.get(0).getName());
                firstButton.setCompoundDrawablePadding(3);
                mDividers.add(firstButton);

                Button secondButton = (Button) findViewById(getViewIdentifier("activity_extendsionbar_divider_strategy"));
                secondButton.setCompoundDrawablesRelativeWithIntrinsicBounds(null,getNavDrawable(navModels.get(1)),null,null);
                secondButton.setText(navModels.get(1).getName());
                secondButton.setCompoundDrawablePadding(3);
                mDividers.add(secondButton);

                Button thirdButton = (Button) findViewById(getViewIdentifier("activity_extendsionbar_divider_customservice"));
                thirdButton.setCompoundDrawablesRelativeWithIntrinsicBounds(null,getNavDrawable(navModels.get(2)),null,null);
                thirdButton.setText(navModels.get(2).getName());
                thirdButton.setCompoundDrawablePadding(3);
                mDividers.add(thirdButton);

                Button fourthButton = (Button) findViewById(getViewIdentifier("activity_extendsionbar_divider_gifts"));
                fourthButton.setCompoundDrawablesRelativeWithIntrinsicBounds(null,getNavDrawable(navModels.get(3)),null,null);
                fourthButton.setText(navModels.get(3).getName());
                fourthButton.setCompoundDrawablePadding(3);
                mDividers.add(fourthButton);

//                mDividers.add((Button) findViewById(getViewIdentifier("activity_extendsionbar_divider_strategy")));
//                mDividers.add((Button) findViewById(getViewIdentifier("activity_extendsionbar_divider_customservice")));
//                mDividers.add((Button) findViewById(getViewIdentifier("activity_extendsionbar_divider_gifts")));

                mDividerDots = new ArrayList<>();
                mDividerDots.add((ImageView) findViewById(getViewIdentifier("activity_extendsionbar_divider_me_dot")));
                mDividerDots.add((ImageView) findViewById(getViewIdentifier("activity_extendsionbar_divider_strategy_dot")));
                mDividerDots.add((ImageView) findViewById(getViewIdentifier("activity_extendsionbar_divider_customservice_dot")));
                mDividerDots.add((ImageView) findViewById(getViewIdentifier("activity_extendsionbar_divider_gifts_dot")));

                WindowMessage message = getIntentWindowMessage();
//                if (message == null) {
//                    clickToActivityCenter(null);
//                } else {
//                    navigateToTab(message);
//                }
                if (message == null) {
                    if(XmlUtils.isRedPackageChannel()){
                        message =new WindowMessage();
                        message.setJumpType("/activity");
                    }else{

                        message =new WindowMessage();
                        message.setNavModel(navModels.get(defaultNav));
//                        message.setNavModel(navModels.get(3));
                    }
                }
                navigateToTab(message);
            }
        }
    }

    private void navigateToTab(WindowMessage message) {
        NavModel model = message.getNavModel();
        if(model!=null){
            clickToMenuView(model);
            return;
        }
        WindowMessageType messageType = message.toMessageType();
        switch (messageType) {
            case NORMAL:
                clickToNormalPage(message.getJumpUrl());
                break;
            case ACTIVITY:
                clickToMenuView(message.getJumpType(),-1,true,message.getAppendString());
//                clickToActivityCenter(null);
                break;
            case CARD:
                clickToMenuView(message.getJumpType(),3,false,message.getAppendString());
//                clickToGameGifts(null);
                break;
            case INTRODUCTION:
                clickToMenuView(message.getJumpType(),1,false,message.getAppendString());
//                clickToGameStrategy(null);
                break;
            case CUSTOMER:
                clickToMenuView(message.getJumpType(),2,false,message.getAppendString());
//                clickToCustomService(null);
                break;
            case USER:
            default:
                clickToMenuView(message.getJumpType(),0,false,message.getAppendString());
//                clickToUserAccount(null);
                break;

        }
    }

    private void closeDrawer() {
        if (isDrawerOpen() && !isDrawerLoading()) {
            final Animation closeDrawerAnimation;

            Configuration config = getResources().getConfiguration();
            if (Configuration.ORIENTATION_PORTRAIT == config.orientation) {
                final int animRes = getAnimationIdentifier("wan_animation_slide_out_bottom");
                closeDrawerAnimation = AnimationUtils.loadAnimation(this, animRes);
            } else {
                final int animRes = getAnimationIdentifier("wan_animation_slide_out_left");
                closeDrawerAnimation = AnimationUtils.loadAnimation(this, animRes);
            }

            closeDrawerAnimation.setAnimationListener(new ExtensionBarDrawerToggle());
            mDrawerContent.startAnimation(closeDrawerAnimation);
        }
    }

    private boolean isDrawerOpen() {
        return mTabbarView != null && (mInflatTabbarViewStub != null || mInflatContentViewStub != null);
    }

    private boolean isDrawerLoading() {
        return isAnimationLoading;
    }

    @Override
    public void onGlobalLayout() {
        WL.d(TAG, "onGlobalLayout  ---> ");
        openDrawer();
    }

    @Override
    public void onClick(View v) {
        if (mContentWebView != null) {
            if (mContentWebView.canGoBack()) {
                final String url = mContentWebView.getUrl();
                WL.d(TAG, "goback ----> url: " + url);
                mLoadUrlStack.remove(url);
                mContentWebView.goBack();
            }
        }
    }


    ChangeFragmentLister changeFragmentLister = new ChangeFragmentLister() {
        @Override
        public void changeToMain() {
            if(JuHaoWanSDK.getInstance().getmRoleInfo()==null){
                Toast.makeText(FloatExtensionBarActivity.this,"请先进入游戏",Toast.LENGTH_SHORT).show();
                return;
            }
            HttpEngineApi.getInstance().getRedPackageInfo(requestCallbackHandler(RedpackageResponseParams.class));

        }

        @Override
        public void changeToDetail() {
            redPackageDetail.updateData(redPackageinfo);
            // 通过FragmentManager对象获得FragmentTransaction对象(开启事务)
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

            fragmentTransaction.replace(redPackageLayout.getId(),redPackageDetail);//动态添加
            fragmentTransaction.commit();//提交  提交  提交（很重要）
        }

        @Override
        public void changeToTixian() {
            redPackageTixian.updateData(redPackageinfo);
            // 通过FragmentManager对象获得FragmentTransaction对象(开启事务)
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

            fragmentTransaction.replace(redPackageLayout.getId(),redPackageTixian);//动态添加
            fragmentTransaction.commit();//提交  提交  提交（很重要）
        }

        @Override
        public void changeToBind() {
            redPackageBind.updateData(redPackageinfo);
            // 通过FragmentManager对象获得FragmentTransaction对象(开启事务)
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

            fragmentTransaction.replace(redPackageLayout.getId(),redPackageBind);//动态添加
            fragmentTransaction.commit();//提交  提交  提交（很重要）
        }

        @Override
        public void getPakage(String packageId) {
            HttpEngineApi.getInstance().goGetRedPackage(packageId,requestCallbackHandler(RedPackageGetResponseParams.class));

        }

        @Override
        public void bindAlipay(String name, String account) {
            HttpEngineApi.getInstance().redPackageBind(name,account,requestCallbackHandler(RedPackageBindResponseParams.class));
        }

        @Override
        public void tixian(String money) {
            HttpEngineApi.getInstance().redPackageCashOut(money,requestCallbackHandler(RedPackageCashOutResponseParams.class));
        }
    };
    //获得FragmentManager对象
    FragmentManager fragmentManager = getSupportFragmentManager();

    RedPackageFragment redpackage =new RedPackageFragment(changeFragmentLister);
    RedPackageDetailFragment redPackageDetail = new RedPackageDetailFragment(changeFragmentLister);
    RedPackageTixianFragment redPackageTixian = new RedPackageTixianFragment(changeFragmentLister);
    RedPackageBindFragment redPackageBind = new RedPackageBindFragment(changeFragmentLister);

    private void setActivityCenterVisible(boolean visible) {
        if(visible&&XmlUtils.isRedPackageChannel()){
            Log.e("float",visible+".."+(redPackageLayout!=null));
                if(redPackageLayout!=null){
                    redPackageLayout.setVisibility(View.VISIBLE);


                    changeFragmentLister.changeToMain();





                }
            }else {
                if(redPackageLayout!=null)redPackageLayout.setVisibility(View.GONE);
            }
//        if (mContentLocalView != null) {
//            mContentLocalView.setVisibility(visible ? View.VISIBLE : View.GONE);
//        }
        if (mContentRemoteView != null) {
            mContentRemoteView.setVisibility(visible ? View.GONE : View.VISIBLE);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        final ActivityPageInfo activityPageInfo = new ActivityPageInfo();
        activityPageInfo.setCurrentUrlIndex(position);
        activityPageInfo.setActivityPageUrlList(mActivityListAdapter.getActivityDetailList());
        ActivityCenterActivity.forwardActivityCenterActivity(this, activityPageInfo);
    }
    public final static int CHOOSER_REQUEST = 0x33;
    // 文件选择回调（在 MainActivity.java 的 onActivityResult中调用此方法）
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void onActivityResultFileChooser(int requestCode, int resultCode, Intent intent) {
        if (requestCode != CHOOSER_REQUEST || uploadFiles == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadFiles.onReceiveValue(results);
        uploadFiles = null;
    }
    private ValueCallback<Uri[]> uploadFiles = null;
    private class ExtensionBarWebChromeClient extends WebChromeClient {
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            uploadFiles = filePathCallback;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            i.setType("*/*"); // 设置文件类型
            String[] mimeTypes = { "image/*,audio/*,video/*,*/*" };
            i.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes); // 设置多种类型
            i.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(Intent.createChooser(i, "Image Chooser"), CHOOSER_REQUEST);
            return true;
        }



        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (!TextUtils.isEmpty(title)) {
                if(title.contains("weixin")){
                    mContentTitle.setText("正在前往微信");
                }else{
                    mContentTitle.setText(title);
                }
            } else {
                mContentTitle.setText(getStringIdentifier("hnssn_float_message"));
            }

        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (mContentProgressBar != null) {
                if (newProgress == 100) {
                    mContentProgressBar.setVisibility(View.GONE);
                } else {
                    if (View.VISIBLE != mContentProgressBar.getVisibility()) {
                        mContentProgressBar.setVisibility(View.VISIBLE);
                    }
                    mContentProgressBar.setProgress(newProgress);
                }

            }
            super.onProgressChanged(view, newProgress);
        }
    }

    private class ExtensionBarWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            WL.d(TAG, "shouldOverrideUrlLoading ---->url: " + url);

            if (url.startsWith(QQ_CUSTOMER_SERVICE)) {
                try {
                    String qq = getValueByName(url, "nameAccount");

                    WL.d(TAG, "shouldOverrideUrlLoading ---->qq: " + qq);

                    String localUrl = "mqqwpa://im/chat?chat_type=wpa&uin=" + qq;
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(localUrl)));
                } catch (ActivityNotFoundException e) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                }
            } else if (url.startsWith(WECHAT_PUBLIC_NUMBER)) {
                if (ToolsUtils.isInstallWeixin(getApplicationContext())) {
                    String originalAppId = getValueByName(url, "id");
                    String appId = getValueByName(url, "appId");

                    ToolsUtils.startWeChatPublicNumber(getApplicationContext(), appId, originalAppId);
                } else {
                    String message = getString(getStringIdentifier("hnssn_hint_wechat_uninstall"));
                    DialogFactory.createConfirmDialog(FloatExtensionBarActivity.this, message).show();
                }
            }else if (url.startsWith("weixin://")){
                startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(url)),123);
            }
            else {
                if (mContentWebView != null) {
                    mContentWebView.loadUrl(url);
                }

                mLoadUrlStack.put(url, url);
            }

            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            WL.d(TAG, "onPageFinished ----> url: " + url);

            if (mLoadUrlStack.isEmpty()) {
                mContentWebViewGoback.setVisibility(View.GONE);
            } else {
                mContentWebViewGoback.setVisibility(View.VISIBLE);
            }
        }
    }


    private class ExtensionBarDrawerToggle implements Animation.AnimationListener {

        @Override
        public void onAnimationStart(Animation animation) {
            WL.d(TAG, "onDrawerOpened ----> ");
            isAnimationLoading = true;
            if (mViewTreeObserver != null && mViewTreeObserver.isAlive()) {
                mViewTreeObserver.removeGlobalOnLayoutListener(FloatExtensionBarActivity.this);
            }
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            WL.d(TAG, "onDrawerClosed ----> ");
            isAnimationLoading = false;
            finish();
            overridePendingTransition(0, 0);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    }

    private class ExtensionBarBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                String action = intent.getAction();
                if (TextUtils.equals(action, Constant.LocalIntentAction.DESTROY_FLOAT_EXTENSIONBAR)) {
                    closeDrawer();
                }
            }
        }
    }

    private class AndroidJavaScriptInterface {

        @JavascriptInterface
        public void readCall(String json) {
            JsonParser jsonParser = new JsonParser();
            JsonElement jsonElement = jsonParser.parse(json);
            if (jsonElement.isJsonArray()) {
                JsonArray jsonArray = jsonElement.getAsJsonArray();
                for (int index = 0; index < jsonArray.size(); index++) {
                    JsonElement jsonObject = jsonArray.get(index);
                    final TabReadStatus status = new Gson().fromJson(jsonObject, TabReadStatus.class);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setTabDividerRedDotVisible(status.getPosition() - 1, status.isReadStatus());
                        }
                    });
                }

            }
        }
        @JavascriptInterface
        public void shareCall(String json) {

            Gson gson = new Gson();
            ActivityPageInfo activityPageInfo =gson.fromJson(json,ActivityPageInfo.class);

            ActivityCenterActivity.forwardActivityCenterActivity(FloatExtensionBarActivity.this, activityPageInfo);
        }

        @JavascriptInterface
        public void swichAccountCall(String json){
            Log.d("test","swichAccountCall");
//            WanSDK.getInstance().logout();
            HttpEngineConduits wanSDKDataDao = HttpEngineApi.getInstance().getEngineConduits();
            wanSDKDataDao.writeAutoLogin(false);
//            WanSDK.getInstance().login();
//
            JuHaoWanSDK.getInstance().logout();
//            JHToolsSDK.getInstance().onSwitchAccount();
//            login();
            CallbackObservable.getInstance().callResponseResult(Constant.CallType.CALL_LOGIN,Constant.LoginState.SWITH_ACCOUNT,"","");
            finish();
        }

        @JavascriptInterface
        public void changePwdCall(String json){
            Log.d("test","changePwdCall");
            HttpEngineConduits wanSDKDataDao = HttpEngineApi.getInstance().getEngineConduits();
            AccountInfo info = wanSDKDataDao.findUserAccountByUserId(wanSDKDataDao.readCurrentLoginUserUID());
            if(info!=null){
                info.setPassword("");
                wanSDKDataDao.saveUserAccount(info);
            }
            wanSDKDataDao.writeAutoLogin(false);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==123){
            if(mContentWebView.canGoBack()){
                mContentWebView.goBack();
            }
        }else if (requestCode == CHOOSER_REQUEST) { // 处理返回的文件
            onActivityResultFileChooser(requestCode, resultCode, data); // 调用 WVChromeClient 类中的 回调方法
        }
    }
}
